package com.huika.dealontop.control.nearby.activity;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.view.AutoScrollViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.reflect.TypeToken;
import com.huika.dealontop.R;
import com.huika.dealontop.config.UrlConstants;
import com.huika.dealontop.control.base.BaseAct;
import com.huika.dealontop.control.nearby.adapter.MerchantDetailAdapter;
import com.huika.dealontop.support.domain.AdvertisementInfo;
import com.huika.dealontop.support.domain.ImageUrlBean;
import com.huika.dealontop.support.domain.MerchantDetailBean;
import com.huika.dealontop.support.domain.OtherGrouponBean;
import com.huika.dealontop.support.domain.ProductDetailsBean;
import com.huika.dealontop.support.domain.UserEvaluationBean;
import com.huika.dealontop.support.domain.UserEvaluationItemBean;
import com.huika.dealontop.support.http.FormResultRequest;
import com.huika.dealontop.support.http.JSONWrapAjaxParams;
import com.huika.dealontop.support.http.RequestResult;
import com.huika.dealontop.utils.DialogUtils;
import com.huika.dealontop.utils.ImageLoaderHelper;
import com.huika.dealontop.utils.ScreenUtil;
import com.huika.dealontop.utils.UIUtils;
import com.huika.dealontop.views.CommonTitleRightWindow;
import com.huika.dealontop.views.IOSAlertDialog;
import com.huika.dealontop.views.TitleBarHelper;
import com.huika.huikalib.utils.MoneyShowTool;
import com.huika.huikalib.utils.NetUtil;
import com.huika.huikalib.utils.StringUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Created by huhao on 2015/11/24.
 */
public class MerchantDetailActivity extends BaseAct {

    private MerchantDetailBean mMerchantDetail;
    private UserEvaluationBean mUserEvaluationList;
    private List<ImageUrlBean> imageList = new ArrayList<ImageUrlBean>();
    public static final String Merchant_ID = "merchant_id";
    public static final String Product_ID = "product_id";
    private String merchantID;
    private String productID;
    private ListView lv_Merchant_list;
    private MerchantDetailAdapter merchantDetailAdapter;
    private CommonTitleRightWindow moreWindow;
    private boolean scrollFlag = false;// 标记是否滑动
    private int lastVisibleItemPosition = 0;// 标记上次滑动位置
    private int size;
    @Override
    public void setRootView() {
        setContentView(R.layout.activity_merchant_detail);
    }

    @Override
    protected void initData() {
        super.initData();
        Intent intent = getIntent();
        if (intent != null) {
            merchantID = intent.getStringExtra(Merchant_ID);
            productID = intent.getStringExtra(Product_ID);
        }
        getHeadList();
        getOtherGrouponList();
        getUserEvaluationList();
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        TitleBarHelper titleBarHelper = new TitleBarHelper(this, R.string.common_empty, R.string.common_empty, R
                .string.Merchant_title);
        titleBarHelper.setRightImg(R.mipmap.icon_common_menu);
        titleBarHelper.setOnRightImgClickListener(this);
        titleBarHelper.setOnLeftClickListener(this);
        moreWindow = new CommonTitleRightWindow(aty);
        lv_Merchant_list = (ListView) findViewById(R.id.lv_Merchant_list);
        lv_Merchant_list.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                switch (scrollState) {
                    // 当不滚动时
                    case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:// 是当屏幕停止滚动时
                        scrollFlag = false;
                        // 判断滚动到底部
                        if (lv_Merchant_list.getLastVisiblePosition() == (lv_Merchant_list.getCount() - 1)) {
                            if (size==10) {
                                getUserMoreEvaluationList();
                            }
                        }

                        break;
                    case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:// 滚动时
                        scrollFlag = true;
                        // 判断滚动到底部
                        if (lv_Merchant_list.getLastVisiblePosition() == (lv_Merchant_list.getCount() - 1)) {

                        }
                        break;
                    case AbsListView.OnScrollListener.SCROLL_STATE_FLING:// 是当用户由于之前划动屏幕并抬起手指，屏幕产生惯性滑动时
                        scrollFlag = false;
                        break;
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if (scrollFlag
                        && ScreenUtil.getScreenViewBottomHeight(lv_Merchant_list) >= ScreenUtil
                        .getScreenHeight(UIUtils.getContext())) {
                    if (firstVisibleItem > lastVisibleItemPosition) {// 上滑
                        if (size==10) {
                            getUserMoreEvaluationList();
                        }

                    } else if (firstVisibleItem < lastVisibleItemPosition) {// 下滑

                    } else {
                        return;
                    }
                    lastVisibleItemPosition = firstVisibleItem;
                }
            }
        });
        getHeadView();
        initAutoScrollViewPage();
        iv_merchant.setVisibility(View.VISIBLE);
        tv_merchant_name.setOnClickListener(this);
        tv_merchant_tel.setOnClickListener(this);
        tv_merchant_location.setOnClickListener(this);
        merchantDetailAdapter = new MerchantDetailAdapter(UIUtils.getContext(), MerchantDetailActivity.this);
        lv_Merchant_list.addHeaderView(getHeadView());
        lv_Merchant_list.setAdapter(merchantDetailAdapter);
        merchantDetailAdapter.notifyDataSetChanged();
    }

    private View mheadView;
    private AutoScrollViewPager<ImageUrlBean> autoviewpage_Merchant_pic;
    private LinearLayout ll_Merchant_dot, ll_merchant_ing;
    private ImageView iv_merchant;
    private RatingBar rb_price, rb_environment, rb_service;
    private TextView tv_price, tv_environment, tv_service, tv_Merchant_pingfennum, tv_Merchant_renshu,
            tv_merchant_name, tv_merchant_time, tv_merchant_tel, tv_merchant_location;

    /**
     * 添加Listview头部视图
     *
     * @return
     */
    private View getHeadView() {
        final LayoutInflater inflater = LayoutInflater.from(UIUtils.getContext());
        if (mheadView == null) {
            mheadView = inflater.inflate(R.layout.head_merchant_detail, null);
            autoviewpage_Merchant_pic = (AutoScrollViewPager<ImageUrlBean>) mheadView
                    .findViewById(R.id.autoviewpage_Merchant_pic);
            ll_Merchant_dot = (LinearLayout) mheadView
                    .findViewById(R.id.Merchant_dotLl);
            ll_merchant_ing = (LinearLayout) mheadView
                    .findViewById(R.id.ll_merchant_ing);
            iv_merchant = (ImageView) mheadView
                    .findViewById(R.id.Merchant__iv);
            rb_price = (RatingBar) mheadView
                    .findViewById(R.id.rb_price);
            rb_environment = (RatingBar) mheadView
                    .findViewById(R.id.rb_environment);
            rb_service = (RatingBar) mheadView
                    .findViewById(R.id.rb_service);
            tv_price = (TextView) mheadView
                    .findViewById(R.id.tv_price);
            tv_environment = (TextView) mheadView
                    .findViewById(R.id.tv_environment);
            tv_service = (TextView) mheadView
                    .findViewById(R.id.tv_service);
            tv_Merchant_pingfennum = (TextView) mheadView
                    .findViewById(R.id.tv_Merchant_pingfennum);
            tv_Merchant_renshu = (TextView) mheadView
                    .findViewById(R.id.tv_Merchant_renshu);
            tv_merchant_name = (TextView) mheadView
                    .findViewById(R.id.tv_merchant_name);
            tv_merchant_time = (TextView) mheadView
                    .findViewById(R.id.tv_merchant_time);
            tv_merchant_tel = (TextView) mheadView
                    .findViewById(R.id.tv_merchant_tel);
            tv_merchant_location = (TextView) mheadView
                    .findViewById(R.id.tv_merchant_location);
        }
        return mheadView;
    }

    private IOSAlertDialog callDialog;

    @Override
    public void widgetClick(View v) {
        super.widgetClick(v);
        switch (v.getId()) {
            case R.id.left://返回
                finish();
                break;
            case R.id.title_right_iv://悬浮菜单
                moreWindow.showWindow(findViewById(R.id.title_right_iv), -UIUtils.dip2px(110), 0);
                break;
            case R.id.tv_merchant_name://跳至商家介绍页面
                Bundle bundle = new Bundle();
                if (mMerchantDetail!=null) {
                    bundle.putString(MerchantIntroductionActivity.Introduce_NAME, mMerchantDetail.getMerchantName());
                    bundle.putString(MerchantIntroductionActivity.Introduce_TIME, mMerchantDetail.getSaleTime());
                    bundle.putString(MerchantIntroductionActivity.Merchant_PHONE, mMerchantDetail.getMerchantPhone());
                    bundle.putString(MerchantIntroductionActivity.Merchant_EXT, mMerchantDetail.getExt());
                    bundle.putString(MerchantIntroductionActivity.Merchant_ADDRESS, mMerchantDetail.getMerchantAddress());
                    bundle.putString(MerchantIntroductionActivity.Merchant_X, mMerchantDetail.getLatitude());
                    bundle.putString(MerchantIntroductionActivity.Merchant_Y, mMerchantDetail.getLongitude());
                    bundle.putParcelable(MerchantIntroductionActivity.Merchant_SERVICE, mMerchantDetail
                            .getMerchantServices());
                    bundle.putString(Merchant_ID, merchantID);
                }
                showActivity(this, MerchantIntroductionActivity.class, bundle);
                break;
            case R.id.tv_merchant_tel://弹出拨打电话框
                if (callDialog == null) {
                    callDialog = DialogUtils.getInstance().createTitleDialog(this, StringUtils.formatTaiPhone
                            (mMerchantDetail.getMerchantPhone()));
                    callDialog.setCancelText(getString(R.string.common_calcle));
                    callDialog.setConfirmText(getString(R.string.comm_call_phone));
                    callDialog.setConfirmClickListener(new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            callDialog.dismiss();
                            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + mMerchantDetail
                                    .getMerchantPhone()));
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                        }
                    });
                }
                callDialog.show();
                break;
            case R.id.tv_merchant_location://跳至地图导航页面
                if (mMerchantDetail == null) {
                    return;
                }
                //打开地图
                Intent intent = new Intent(this, GMapActivity.class);
                intent.putExtra(GMapActivity.MERCHANTNAME, mMerchantDetail.getMerchantName());
                intent.putExtra(GMapActivity.MERCHANTADDRESS, mMerchantDetail.getMerchantAddress());
                intent.putExtra(GMapActivity.MERCHANTLAT, mMerchantDetail.getLatitude());
                intent.putExtra(GMapActivity.MERCHANTLNG, mMerchantDetail.getLongitude());
                this.startActivity(intent);
                break;
        }
    }

    @Override
    public void onErrorResponse(VolleyError error) {
        super.onErrorResponse(error);
        dismissLoadingDialog();
        if (CURRENT_PAGE == 1 && NetUtil.hasAvailableNet(UIUtils.getContext()
        ) == false) {
            setNetErrorClick(reloaClickListener);
        } else if (CURRENT_PAGE == 1 && NetUtil.hasAvailableNet(UIUtils
                .getContext()) ==
                true) {

        }
    }

    private View.OnClickListener reloaClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // 第一页就加载失败了
            hideOverLay();
            showLoadingDialog("\t");
            getHeadList();
            getOtherGrouponList();
            getUserEvaluationList();
        }
    };

    /**
     * 获取商家主页头部列表信息
     */
    private void getHeadList() {
        showLoadingDialog("\t");
        JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
        ajaxParams.putCommonTypeParam("MerchantID", merchantID);
        FormResultRequest<MerchantDetailBean> request = new FormResultRequest<MerchantDetailBean>(UrlConstants
                .MERCHANTDETAIL, mgetHeadList, this, new TypeToken<RequestResult<MerchantDetailBean>>() {
        }.getType());
        request.setRequestParams(ajaxParams);
        executeRequest(request);
    }

    private Response.Listener<RequestResult<MerchantDetailBean>> mgetHeadList = new
            Response.Listener<RequestResult<MerchantDetailBean>>() {
                @Override
                public void onResponse(RequestResult<MerchantDetailBean> Result) {
                    dismissLoadingDialog();
                    if (Result.flag == 1) {
                        mMerchantDetail = new MerchantDetailBean();
                        mMerchantDetail = Result.getRs();
                        showHeadMess(mMerchantDetail);
                    }
                }
            };

    //显示联网后头部信息
    private void showHeadMess(MerchantDetailBean mMerchantDetail) {
        if (!StringUtils.isEmpty(mMerchantDetail.getMerchantImage())) {
            iv_merchant.setVisibility(View.GONE);
            imageList.clear();
            for (String iterable_element : convertStrToArray(mMerchantDetail.getMerchantImage())) {
                ImageUrlBean ib = new ImageUrlBean();
                ib.setImageUrl(iterable_element);
                imageList.add(ib);
            }
            initAdvertisementInfoDatas();

        } else if (!StringUtils.isEmpty(mMerchantDetail.getBrandLogoURL())) {
            iv_merchant.setVisibility(View.VISIBLE);
            ImageLoaderHelper.displayImage(mMerchantDetail.getBrandLogoURL(), iv_merchant);
        } else {
            iv_merchant.setVisibility(View.VISIBLE);
            iv_merchant.setImageResource(R.mipmap.morenpic);
        }
        rb_price.setRating(Float.parseFloat(MoneyShowTool.formatOne(mMerchantDetail.getCost())));
        tv_price.setText(MoneyShowTool.formatOne(mMerchantDetail.getCost()) + "");
        rb_environment.setRating(Float.parseFloat(MoneyShowTool.formatOne(mMerchantDetail.getEnvironment())));
        tv_environment.setText(MoneyShowTool.formatOne(mMerchantDetail.getEnvironment()) + "");
        rb_service.setRating(Float.parseFloat(MoneyShowTool.formatOne(mMerchantDetail.getServices())));
        tv_service.setText(MoneyShowTool.formatOne(mMerchantDetail.getServices()) + "");
        tv_Merchant_pingfennum.setText(MoneyShowTool.formatOne(mMerchantDetail.getProductAvgEvaluate()) + "");
        tv_Merchant_renshu.setText(String.format(context.getString(R.string
                .Merchant_pingjianum), mMerchantDetail.getEvaluateNum()));
        tv_merchant_name.setText(mMerchantDetail.getMerchantName() + "");
        tv_merchant_time.setText(getString(R.string.Merchant_time) + mMerchantDetail.getSaleTime());
        if (!StringUtils.isEmpty(mMerchantDetail.getExt())) {
            tv_merchant_tel.setText(StringUtils.formatTaiPhone(mMerchantDetail.getMerchantPhone()) + getString(R
                    .string.common_ext) + mMerchantDetail.getExt());
        } else {
            tv_merchant_tel.setText(StringUtils.formatTaiPhone(mMerchantDetail.getMerchantPhone()));
        }
        tv_merchant_location.setText(mMerchantDetail.getMerchantAddress());
    }
    /*初始化轮播图*/

    private void initAutoScrollViewPage() {
        autoviewpage_Merchant_pic.setScaleType(ImageView.ScaleType.FIT_XY);
        autoviewpage_Merchant_pic.setClickable(true);
        //加载默认图片
        autoviewpage_Merchant_pic.setImageOptions(new DisplayImageOptions.Builder().showImageOnLoading(R.mipmap
                .morenpic)
                .showImageForEmptyUri(R.mipmap.morenpic).showImageOnFail(R.mipmap.morenpic).cacheInMemory
                        (true)// 开启内存缓存
                .cacheOnDisk(true) // 开启硬盘缓存
                .resetViewBeforeLoading(false).build());

        getHeadList();
    }

    private void initAdvertisementInfoDatas() {
        iv_merchant.setVisibility(View.GONE);
        autoviewpage_Merchant_pic.refreshDatas(imageList, ll_Merchant_dot, false, true);
        autoviewpage_Merchant_pic.start(3000);
    }

    //使用String的split方法
    private String[] convertStrToArray(String str) {
        String[] strArray = null;
        strArray = str.split(","); //拆分字符为"," ,然后把结果交给数组strArray
        return strArray;
    }

    /**
     * 获取商家主页其它商品列表
     */
    private void getOtherGrouponList() {
        showLoadingDialog("\t");
        JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
        if (!"0".equals(productID) || !StringUtils.isEmpty(productID)) {
            ajaxParams.putCommonTypeParam("ProductId", productID);
        }
        ajaxParams.putCommonTypeParam("MerchantID", merchantID);
        ajaxParams.putCommonTypeParam("Page", CURRENT_PAGE);
        ajaxParams.putCommonTypeParam("PageSize", PAGE_SIZE);
        FormResultRequest<List<OtherGrouponBean>> request = new FormResultRequest<List<OtherGrouponBean>>(UrlConstants
                .OTHERGROUPONLIST, mgetOtherGrouponList, this, new TypeToken<RequestResult<List<OtherGrouponBean>>>() {
        }.getType());
        request.setRequestParams(ajaxParams);
        executeRequest(request);
    }

    /**
     * 获取商家主页其它商品列表
     */
    public void getOtherGrouponListMore() {
        showLoadingDialog("\t");
        CURRENT_PAGE++;
        JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
        if (!"0".equals(productID) || !StringUtils.isEmpty(productID)) {
            ajaxParams.putCommonTypeParam("ProductId", productID);
        }
        ajaxParams.putCommonTypeParam("MerchantID", merchantID);
        ajaxParams.putCommonTypeParam("Page", CURRENT_PAGE);
        ajaxParams.putCommonTypeParam("PageSize", PAGE_SIZE);
        FormResultRequest<List<OtherGrouponBean>> request = new FormResultRequest<List<OtherGrouponBean>>(UrlConstants
                .OTHERGROUPONLIST, mgetOtherGrouponList, this, new TypeToken<RequestResult<List<OtherGrouponBean>>>() {
        }.getType());
        request.setRequestParams(ajaxParams);
        executeRequest(request);
    }


    private Response.Listener<RequestResult<List<OtherGrouponBean>>> mgetOtherGrouponList = new
            Response.Listener<RequestResult<List<OtherGrouponBean>>>() {
                @Override
                public void onResponse(RequestResult<List<OtherGrouponBean>> Result) {
                    dismissLoadingDialog();
                    if (Result.getRs() != null && Result.getRs().size() > 0) {
                        if (Result.getRs().size() == 10) {
                            merchantDetailAdapter.hasMoreGroupon = true;
                        } else {
                            merchantDetailAdapter.hasMoreGroupon = false;
                        }
                    }
                    if (Result.getRs() == null) {
                        ll_merchant_ing.setVisibility(View.GONE);
                    } else {
                        ll_merchant_ing.setVisibility(View.VISIBLE);
                    }

                    if (Result.flag == 1) {
                        if (Result.getRs() != null && Result.getRs().size() > 0) {
                            if (merchantDetailAdapter.mOtherGrouponList != null) {
                                merchantDetailAdapter.mOtherGrouponList.addAll(Result.getRs());
                            } else {
                                merchantDetailAdapter.mOtherGrouponList = Result.getRs();
                            }
                            merchantDetailAdapter.notifyDataSetChanged();
                        }
                    }
                }
            };

    /**
     * 获取商家主页评价信息
     */
    private void getUserMoreEvaluationList() {
        showLoadingDialog("\t");
        CURRENT_PAGE++;
        int type = 0;
        JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
        if (!"0".equals(productID) && !StringUtils.isEmpty(productID) && productID != null) {
            type = 1;
            ajaxParams.putCommonTypeParam("productID", productID);
        } else {
            type = 2;
            ajaxParams.putCommonTypeParam("MerchantID", merchantID);
        }
        ajaxParams.putCommonTypeParam("type", type);
        ajaxParams.putCommonTypeParam("pageNo", CURRENT_PAGE);
        ajaxParams.putCommonTypeParam("pageSize", PAGE_SIZE);
        FormResultRequest<UserEvaluationBean> request = new FormResultRequest<UserEvaluationBean>
                (UrlConstants
                        .USEREVALUATION, mgetUserEvaluationList, this, new
                        TypeToken<RequestResult<UserEvaluationBean>>
                                () {
                        }.getType());
        request.setRequestParams(ajaxParams);
        executeRequest(request);
    }
    /**
     * 获取商家主页评价信息
     */
    private void getUserEvaluationList() {
        showLoadingDialog("\t");
        int type = 0;
        JSONWrapAjaxParams ajaxParams = new JSONWrapAjaxParams();
        if (!"0".equals(productID) && !StringUtils.isEmpty(productID) && productID != null) {
            type = 1;
            ajaxParams.putCommonTypeParam("productID", productID);
        } else {
            type = 2;
            ajaxParams.putCommonTypeParam("MerchantID", merchantID);
        }
        ajaxParams.putCommonTypeParam("type", type);
        ajaxParams.putCommonTypeParam("pageNo", CURRENT_PAGE);
        ajaxParams.putCommonTypeParam("pageSize", PAGE_SIZE);
        FormResultRequest<UserEvaluationBean> request = new FormResultRequest<UserEvaluationBean>
                (UrlConstants
                        .USEREVALUATION, mgetUserEvaluationList, this, new
                        TypeToken<RequestResult<UserEvaluationBean>>
                                () {
                        }.getType());
        request.setRequestParams(ajaxParams);
        executeRequest(request);
    }

    private Response.Listener<RequestResult<UserEvaluationBean>> mgetUserEvaluationList = new
            Response.Listener<RequestResult<UserEvaluationBean>>() {
                @Override
                public void onResponse(RequestResult<UserEvaluationBean> Result) {
                    dismissLoadingDialog();
                    if (Result.flag == 1) {
                        mUserEvaluationList = Result.getRs();
                        if (merchantDetailAdapter.mUserEvaluationList != null) {
                            merchantDetailAdapter.mUserEvaluationList.addAll(mUserEvaluationList.getNodes());
                        } else {
                            merchantDetailAdapter.mUserEvaluationList = mUserEvaluationList.getNodes();
                        }
                        size = mUserEvaluationList.getNodes().size();
                        merchantDetailAdapter.notifyDataSetChanged();
                    }
                }
            };
}
